package com.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.entity.User;
import com.demo.mapper.ClusterMapper;
import com.demo.service.ClusterService;
import com.demo.service.impl.ClusterServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JsonController {

    @Autowired
    ClusterMapper clusterMapper;

    /**
     * 通过URL地址获取json串
     * @return
     */
    @ResponseBody
    @RequestMapping("/test")
    public String getJson() {
        ClusterService clusterService = new ClusterServiceImpl();
        JSONObject jsonObject = ((ClusterServiceImpl) clusterService).showJsonByGet("https://way.jd.com/" +
                "jisuapi/weather" + "?city=福州&cityid=&citycode=&appkey=f634a813404380693717a5f61cb33170");
        return jsonObject.toJSONString();

    }

    /**
     * 将json串插入数据库
     * @return
     */
    @ResponseBody
    @RequestMapping("/insert")
    public String test1() {
        clusterMapper.insertJson(1,"test","test",
                Timestamp.valueOf("2019-04-13 20:00:00"), 1.1);
        return "插入成功";
    }

    /**
     * 测试 @RequestBody注解
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testGet", method = RequestMethod.GET)
    public String test2(@RequestParam(value = "name", required = false) String name) {

        return name;
    }

    /**
     * 测试@RequestBody
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testPost", method = RequestMethod.POST)
    public String test3(@RequestBody User user, @RequestParam("name") String name) {

        return name;
    }

    @ResponseBody
    @RequestMapping("/a")
    public String a(@RequestBody List<Object> list) {

        for (Object o : list) {
            System.out.println(o);
        }
        return "接收成功";
    }

    /**
     * get方法
     * @param id
     * @param name
     */
    @ResponseBody
    @GetMapping("/b")
    public User getMethod(@RequestParam("id") Integer id,
                         @RequestParam("name") String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);

        return user;
    }

    /**
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/c")
    public String gets() {
       return "[{\"name\":\"1\"},{\"name\":\"2\"}]";
    }

}
